package com.zziq.mianshi.controller;


import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zziq.mianshi.annotation.AuthCheck;
import com.zziq.mianshi.common.BaseResponse;
import com.zziq.mianshi.common.DeleteRequest;
import com.zziq.mianshi.common.ErrorCode;
import com.zziq.mianshi.common.ResultUtils;
import com.zziq.mianshi.constant.UserConstant;
import com.zziq.mianshi.exception.BusinessException;
import com.zziq.mianshi.exception.ThrowUtils;
import com.zziq.mianshi.manager.CounterManager;
import com.zziq.mianshi.model.dto.question.*;
import com.zziq.mianshi.model.dto.questionBank.QuestionBankQueryRequest;
import com.zziq.mianshi.model.entity.Question;
import com.zziq.mianshi.model.entity.QuestionBankQuestion;
import com.zziq.mianshi.model.entity.User;
import com.zziq.mianshi.model.vo.QuestionBankVO;
import com.zziq.mianshi.model.vo.QuestionVO;
import com.zziq.mianshi.service.QuestionBankQuestionService;
import com.zziq.mianshi.service.QuestionService;
import com.zziq.mianshi.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 题目接口
 */
@RestController
@RequestMapping("/question")
@Slf4j
@Api(tags = "题目 相关业务")
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    private QuestionBankQuestionService questionBankQuestionService;

    // region 增删改查

    /**
     * 创建题目
     *
     * @param questionAddRequest
     * @param request
     * @return
     */
    @ApiOperation("创建题目")
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)

    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(questionAddRequest == null, ErrorCode.PARAMS_ERROR);

        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);

        // 数据校验
        questionService.validQuestion(question, true);

        // todo 填充默认值
        List<String> tags = questionAddRequest.getTags();
        if (tags != null) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }


        User loginUser = userService.getLoginUser(request);
        if (loginUser != null) {
            question.setUserId(loginUser.getId());
        }

        // 写入数据库
        boolean result = questionService.save(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newQuestionId = question.getId();
        return ResultUtils.success(newQuestionId);
    }

    /**
     * 删除题目
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @ApiOperation("删除题目")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新题目（仅管理员可用）
     *
     * @param questionUpdateRequest
     * @return
     */
    @ApiOperation("更新题目")
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)

    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);

        //得到questionEditRequest 中的 tag属性（List类型）
        List<String> tags = questionUpdateRequest.getTags();
        if (tags != null) {
            //不为空，将List转换为 string（json） 类型 存入  question对象
            question.setTags(JSONUtil.toJsonStr(tags));
        }

        // 数据校验
        questionService.validQuestion(question, false);
        // 判断是否存在
        long id = questionUpdateRequest.getId();
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = questionService.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取题目（封装类）
     *
     * @param id
     * @return
     */
    @ApiOperation("根据题目id获取题目")
    @GetMapping("/get/vo")
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);

        //检测爬虫
        Long userId = userService.getLoginUser(request).getId();
//        crawlerDetect(userId);

        // 查询数据库
        Question question = questionService.getById(id);
        ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND_ERROR);

        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }

    @Resource
    private CounterManager counterManager;

    /**
     * 废弃方法
     * @param loginUserId
     */
//    private void crawlerDetect(long loginUserId){
//        //10次：告警
//        final int WARN_COUNT = 10;
//        //20次：封禁
//        final int bAN_COUNT = 20;
//        //拼接访问的key
//        String key = "user:access:%s" + loginUserId;
//        //获取一分钟内的访问次数
//        long count = counterManager.incrAndGetCounter(key, 1, TimeUnit.MINUTES, 180);
//        //达到20次
//        if (count >= bAN_COUNT) {
//            //强制下线
//            StpUtil.kickout(loginUserId);
//
//            //封禁
//            User updateUser = new User();
//            updateUser.setId(loginUserId);
//            updateUser.setUserRole("ban");
//            userService.updateById(updateUser);
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "访问次数过多，已被封禁");
//        }
//
//        //达到10次
//        if (count == WARN_COUNT) {
//            //警告
//            throw new BusinessException(110, "警告！，访问太频繁！");
//        }
//    }



    /**
     * 分页获取题目列表（仅管理员可用）
     *
     * @param questionQueryRequest
     * @return
     */
    @ApiOperation("分页获取题目列表admin")
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)

    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest) {
        ThrowUtils.throwIf(questionQueryRequest == null, ErrorCode.PARAMS_ERROR);

        return ResultUtils.success(questionService.listQuestionByPage(questionQueryRequest));
    }

    /**
     * 分页获取题目列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @ApiOperation("分页获取题目列表user")
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {
        long size = questionQueryRequest.getPageSize();

        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage
                = questionService.listQuestionByPage(questionQueryRequest);

        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }
    /**
     * 分页获取题目列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @ApiOperation("sentinel分页获取题目列表user")
    @PostMapping("/list/page/vo/sentinel")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPageSentinel(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {
        long size = questionQueryRequest.getPageSize();

        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        //基于id限流
        String remoteAddr = request.getRemoteAddr();
        Entry entry = null;
        try {
            entry = SphU.entry(
                    "listQuestionVOByPageSentinel",//保护的资源名称
                    EntryType.IN,
                    1,//请求一次，记录的次数
                    remoteAddr);  //参数
            //执行业务
            // 查询数据库
            Page<Question> questionPage
                    = questionService.listQuestionByPage(questionQueryRequest);

            // 获取封装类
            return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));

        } catch (Throwable ex) {
            //业务异常
            if(!BlockException.isBlockException(ex)){
                Tracer.trace(ex);
                return ResultUtils.error(ErrorCode.SYSTEM_ERROR,"系统异常sentenel！");
            }
            //降级操作
            if(ex instanceof DegradeException){
                return handleFallback(questionQueryRequest,request,ex);
            }
            //限流操作
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR,"访问过于频繁,请稍后再试");
        } finally {
            if(entry != null) {
                entry.exit(1,remoteAddr);
            }
        }
    }


    /**
     * 处理熔断之后的降级、和限流操作
     * listQuestionBankVOByPage 降级操作：直接返回本地数据
     */
    public BaseResponse<Page<QuestionVO>> handleFallback(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                         HttpServletRequest request, Throwable ex) {
        // 可以返回本地数据或空数据
        return ResultUtils.success(null);
    }

    /**
     * 分页获取当前登录用户创建的题目列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @ApiOperation("分页获取登录用户的题目列表")
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(questionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 编辑题目（给用户使用）
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @ApiOperation("编辑题目")
    @PostMapping("/edit")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)

    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);

        //得到questionEditRequest 中的 tag属性（List类型）
        List<String> tags = questionEditRequest.getTags();
        if (tags != null) {
            //不为空，将List转换为 string（json） 类型 存入  question对象
            question.setTags(JSONUtil.toJsonStr(tags));
        }

        // 数据校验
        questionService.validQuestion(question, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = questionEditRequest.getId();
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionService.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @ApiOperation("分页查询题目")
    @PostMapping("/search/page/vo")
    public BaseResponse<Page<QuestionVO>> searchQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                                 HttpServletRequest request) {
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 200, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.searchFromEs(questionQueryRequest);
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    @ApiOperation("批量删除题目")
    @PostMapping("/delete/batch")
    public BaseResponse<Boolean> batchRemoveQuestion(@RequestBody QuestionBatchRemoveRequest questionBatchRemoveRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(questionBatchRemoveRequest == null,ErrorCode.PARAMS_ERROR,"参数不能为空");
        List<Long> questionIdList = questionBatchRemoveRequest.getQuestionIdList();

        questionService.batchRemoveQuestion(questionIdList);

        User loginUser = userService.getLoginUser(request);
        log.debug("用户id:{},批量删除题目{}",loginUser.getId(), questionIdList);
        return ResultUtils.success(true);
    }

        // endregion
}
